﻿/**
* Dto.js
* 
* @author Demis Bellot
* @version 1.0
* @requires Class.js
* 
* Copyright 2009, Demis Bellot
* http://code.google.com/p/ajaxstack/
*/

function Dto() { }

Dto.CHAR_A = "A".charCodeAt(0);
Dto.CHAR_Z = "Z".charCodeAt(0);
Dto.MULTI_FIELD_SEPERATOR = ";";

Dto.parseGuid = function(guid)
{
	return guid.toLowerCase().replace(/-/g, "");
}
Dto.parseBool = function(aBool)
{
	if (is.Boolean(aBool)) return aBool;
	if (is.String(aBool)) return aBool.toString().toLowerCase() == "true";
	return aBool;
}
Dto.parseArrayOfId = function(array)
{
	return array || [];
}
Dto.parseArrayOfKvp = function(kvps)
{
	if (!kvps) return {};
	
	var result = {};
	for (var i = 0, len = kvps.length; i < len; i++)
	{
		var kvp = kvps[i];
		result[kvp['K']] = kvp['V'];
	}
	return result;
}
Dto.toGetArray = function(array)
{
	return array ? array.join(",") : [];
}
Dto.toPostArray = function(array)
{
	return array || [];
}
Dto.toUtcDate = function(date)
{
	return date.getUTCFullYear()
		+ '-' + S.lpad(date.getUTCMonth() + 1, 2)
		+ '-' + S.lpad(date.getUTCDate(), 2)
		+ 'T' + S.lpad(date.getUTCHours(), 2)
		+ ':' + S.lpad(date.getUTCMinutes(), 2)
		+ ':' + S.lpad(date.getUTCSeconds(), 2)
		+ 'Z';
}
Dto.toJsonDate = function(date)
{
	return "\/Date(" + date.getTime() + "-0000)\/";
}
Dto.toNumber = function(obj)
{
	return isNaN(obj) ? 0 : obj;
}
Dto.toDto = function(obj)
{
	if (!obj || is.Function(obj)) return null;

	//If they have defined their own toDto method use that instead
	if (obj.toDto) return obj.toDto();

	if (is.Array(obj))
	{
		var arrayOfDto = [];
		for (var i in obj)
		{
			arrayOfDto.push(Dto.toDto(obj[i]));
		}
		return arrayOfDto;
	}

	if (is.String(obj) || is.Boolean(obj)) return obj;

	if (is.Number(obj)) return Dto.toNumber(obj);

	if (is.Date(obj)) return Dto.toDate(obj);

	return Dto.cloneObjectWithPascalFields(obj);
}
Dto.cloneObjectWithPascalFields = function(obj)
{
	var clone = {};
	for (var fieldName in obj)
	{
		var firstChar = fieldName.charCodeAt(0);
		var startsWithCapital = firstChar >= Dto.CHAR_A && firstChar <= Dto.CHAR_Z;
		if (startsWithCapital)
		{
			clone[fieldName] = Dto.toDto(obj[fieldName]);
		}
	}
	return clone;
}
Dto.parseKeyValuePairs = function(oKvps)
{
	var results = {};
	for (var i in oKvps)
	{
		var result = objResults[i];
		var name = result.K;
		var value = result.V;
		results[name] = value;
	}
	return results;
}




